package com.sx.manage.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.sx.cache.Cache;
import com.sx.cache.Session;
import com.sx.manage.service.function.FunctionInfoWebService;
import com.sx.manage.util.SessionManager;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.constants.type.MUrlType;
import com.sx.model.manage.mybatis.vo.result.ResultObjectVO;

public class HandlerExceptionResolverImpl extends SimpleMappingExceptionResolver {
	/** 日志 **/
	private Logger _log = LoggerFactory.getLogger(this.getClass());

	private FunctionInfoWebService functionInfoWebService;

	protected Cache redisCache;

	public Cache getRedisCache() {
		return redisCache;
	}

	public void setRedisCache(Cache redisCache) {
		this.redisCache = redisCache;
	}

	public Logger get_log() {
		return _log;
	}

	public void set_log(Logger _log) {
		this._log = _log;
	}

	public FunctionInfoWebService getFunctionInfoWebService() {
		return functionInfoWebService;
	}

	public void setFunctionInfoWebService(FunctionInfoWebService functionInfoWebService) {
		this.functionInfoWebService = functionInfoWebService;
	}

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		String viewName = determineViewName(ex, request);
		if (StringUtils.isNotBlank(viewName)) {
			_log.debug("异常配置了跳转，现在开始跳转");
			request.setAttribute("error", ex.getMessage());
			ModelAndView modelView = getModelAndView(viewName, ex);
			modelView.addObject("error", ex.getMessage());
			return modelView;
		}

		Session session = SessionManager.instance(request, response, redisCache);
		String requestUrl = session.get(MSystemConstants.CURRENT_URL);
		_log.error("未捕获异常：" + ex.getMessage());
		_log.error("未捕获异常：" + ex.getStackTrace()[0]);
		ResultObjectVO<MUrlType> typeResult = functionInfoWebService.getMUrlTypeByUrl(requestUrl);
		MUrlType type = null;
		if (typeResult.isSuccess()) {
			type = typeResult.getObjVo();
			if (MUrlType.AXAJ_URL.equals(type)) {
				_log.debug("requestUrl:" + requestUrl);
				// 没有配置权限，ajax请求url
				// throw new MAjaxErrorException();//返回到配置文件中定义的路径
				viewName = "redirect:/entry/ajaxNotCaughtException";
			} else if (MUrlType.MODEL_AND_VIEW_URL.equals(type)) {
				_log.debug("requestUrl:" + requestUrl);
				// 没有配置权限，界面跳转请求url
				// throw new MViewAndModelException();//返回到配置文件中定义的路径
				viewName = "redirect:/entry/modelNotCaughtException";
			}
		}
		return getModelAndView(viewName, ex);

	}
}